package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.WebRecycleType;
import com.ruoyi.system.domain.WebServerOrder;
import com.ruoyi.system.domain.WebServerUser;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.*;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.util.*;

/**
 * 部门管理 服务实现
 *
 * @author liupan
 */
@Service
public class SysDeptServiceImpl implements ISysDeptService {
    @Autowired
    private SysDeptMapper deptMapper;

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<SysDept> selectDeptList(SysDept dept) {
        return deptMapper.selectDeptList(dept);
    }

    public List<Map<String, Object>> selectDistance(SysDept dept) {
        return deptMapper.selectDistance(dept);
    }

    public List<Map<String, Object>> selectDistanceNoLat(SysDept dept) {
        return deptMapper.selectDistanceNoLat(dept);
    }

    /**
     * 查询部门管理树
     *
     * @param dept 部门信息
     * @return 所有部门信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Ztree> selectDeptTree(SysDept dept) {
        List<SysDept> deptList = deptMapper.selectDeptList(dept);
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    /**
     * 查询部门管理树（排除下级）
     *
     * @param dept 部门ID
     * @return 所有部门信息
     */
    @Override
    @DataScope(deptAlias = "d")
    public List<Ztree> selectDeptTreeExcludeChild(SysDept dept) {
        Long deptId = dept.getDeptId();
        List<SysDept> deptList = deptMapper.selectDeptList(dept);
        Iterator<SysDept> it = deptList.iterator();
        while (it.hasNext()) {
            SysDept d = (SysDept) it.next();
            if (d.getDeptId().intValue() == deptId
                    || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), deptId + "")) {
                it.remove();
            }
        }
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    /**
     * 根据角色ID查询部门（数据权限）
     *
     * @param role 角色对象
     * @return 部门列表（数据权限）
     */
    @Override
    public List<Ztree> roleDeptTreeData(SysRole role) {
        Long roleId = role.getRoleId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<SysDept> deptList = selectDeptList(new SysDept());
        if (StringUtils.isNotNull(roleId)) {
            List<String> roleDeptList = deptMapper.selectRoleDeptTree(roleId);
            ztrees = initZtree(deptList, roleDeptList);
        } else {
            ztrees = initZtree(deptList);
        }
        return ztrees;
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysDept> deptList) {
        return initZtree(deptList, null);
    }

    /**
     * 对象转部门树
     *
     * @param deptList     部门列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysDept> deptList, List<String> roleDeptList) {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (SysDept dept : deptList) {
            if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
                Ztree ztree = new Ztree();
                ztree.setId(dept.getDeptId());
                ztree.setpId(dept.getParentId());
                ztree.setName(dept.getDeptName());
                ztree.setTitle(dept.getDeptName());
                if (isCheck) {
                    ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
                }
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    /**
     * 查询部门人数
     *
     * @param parentId 部门ID
     * @return 结果
     */
    @Override
    public int selectDeptCount(Long parentId) {
        SysDept dept = new SysDept();
        dept.setParentId(parentId);
        return deptMapper.selectDeptCount(dept);
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        int result = deptMapper.checkDeptExistUser(deptId);
        return result > 0 ? true : false;
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    public int deleteDeptById(Long deptId) {
        return deptMapper.deleteDeptById(deptId);
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public int insertDept(SysDept dept) {
        SysDept info = deptMapper.selectDeptById(dept.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new BusinessException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + "," + dept.getParentId());
        return deptMapper.insertDept(dept);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDept(SysDept dept) {
        SysDept newParentDept = deptMapper.selectDeptById(dept.getParentId());
        SysDept oldDept = selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        int result = deptMapper.updateDept(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatus(dept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatus(SysDept dept) {
        String updateBy = dept.getUpdateBy();
        dept = deptMapper.selectDeptById(dept.getDeptId());
        dept.setUpdateBy(updateBy);
        deptMapper.updateDeptStatus(dept);
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = deptMapper.selectChildrenDeptById(deptId);
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            deptMapper.updateDeptChildren(children);
        }
    }

    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    @Override
    public SysDept selectDeptById(Long deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public int selectNormalChildrenDeptById(Long deptId) {
        return deptMapper.selectNormalChildrenDeptById(deptId);
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDept dept) {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept info = deptMapper.checkDeptNameUnique(dept.getDeptName(), dept.getParentId());
        if (StringUtils.isNotNull(info) && info.getDeptId().longValue() != deptId.longValue()) {
            return UserConstants.DEPT_NAME_NOT_UNIQUE;
        }
        return UserConstants.DEPT_NAME_UNIQUE;
    }

    /**
     * 查询技师的可用时间
     *
     * @param deptId
     * @return
     */
    public List<String> selectServerUserTime(String preDay, Long deptId, Integer serverUserId, Boolean validatePreTime) {
        Integer weekOfDayPre = null;
        try {
            preDay = preDay.replace("/","-");
            Date preDate = DateUtils.parseDate(preDay, DateUtils.YYYY_MM_DD);
            preDay = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, preDate);
            //获取是星期几
            weekOfDayPre = DateUtils.getWeekOfDay(preDate);

        } catch (ParseException e) {
            e.printStackTrace();
        }

        List<String> timeList2 = new ArrayList<>();
        SysDept dept = iSysDeptService.selectDeptById(deptId);
        if (weekOfDayPre != null) {
            String noWorks = dept.getNoWorks();
            if (StringUtils.isNotEmpty(noWorks)) {
                String[] noWorksArr = noWorks.split(",");
                if (Arrays.asList(noWorksArr).contains(weekOfDayPre + "")) {
                    throw new BusinessException("抱歉，" + preDay + "门店休息，不能预约");
                }
            }
        }

        if (dept != null && DateUtils.getNowDate().before(DateUtils.addDays(DateUtils.parseDate(preDay), 1))) {
            WebServerUser serverUser = iWebServerUserService.getById(serverUserId);
            //判断技师是否休息
            if (StringUtils.isNotEmpty(serverUser.getNoWorks())) {
                String[] noWorksArr = serverUser.getNoWorks().split(",");
                if (weekOfDayPre != null) {
                    if (Arrays.asList(noWorksArr).contains(weekOfDayPre + "")) {
                        return timeList2; //技师休息的话直接返回
                    }
                }
            }

            String times = serverUser.getTimes();
            if (StringUtils.isNotEmpty(times)) {
                Date parseData = DateUtils.parseDate(DateUtils.getDate());
                if(parseData == null){
                    throw new BusinessException("请选择正确的日期");
                }
                boolean isSameDay = DateUtils.isSameDay(DateUtils.parseDate(preDay), parseData);
                List<String> timeList = new ArrayList<>(Arrays.asList(times.split(",")));
                if (isSameDay) {
                    //把同天的数据移除
                    Iterator<String> it = timeList.iterator();
                    while (it.hasNext()) {
                        String d = preDay + " " + it.next().split("-")[0] + ":00";
                        Date preDate_ = DateUtils.parseDate(d);
                        preDate_ = DateUtils.addHours(preDate_, -1); //预留一个小时
                        Date dd = new Date();
                        if (dd.after(preDate_)) {
                            it.remove();
                        }

                    }
                }

                List<WebServerOrder> webServerOrders = iWebServerOrderService.list(new QueryWrapper<WebServerOrder>()
                        .eq("server_user_id", serverUserId)
                        .eq("dept_id", deptId)
                        .eq("pre_day", preDay)
                        .ne("status",3)
                        .select("pre_time", "recycle_type_id","pre_day")
                );
                for (WebServerOrder order : webServerOrders) {
                    Iterator<String> it = timeList.iterator();

                    if (order.getRecycleTypeId() != null) {
                        //比如订单里包含白转黑设置的是2个小时，则自动把下一个时间段给移除掉
                        WebRecycleType recycleType = webRecycleTypeService.selectWebRecycleTypeById(order.getRecycleTypeId());
                        if (recycleType != null) {
                            Integer timeNum = null;
                            try {
                                timeNum = Integer.valueOf(recycleType.getComment());
                            } catch (Exception e) {
                                logger.error("服务项目时间段转换出错" + e.getMessage());
                            }
                                if (timeNum != null) {
                                    for (int i = 1; i < timeNum; i++) {
                                        Integer preTime = Integer.valueOf(order.getPreTime().split("-")[0].split(":")[0]);
                                        String d_ = (preTime + 1) + ":00" + "-" + (preTime + 2) + ":00";

                                        String compileTime = order.getPreDay()+" "+ order.getPreTime().split("-")[1]+":00";

                                        //验证 比如说白转黑是2个小时时间段，11点有空，但是12点被预约了，此时如果选择11点则不可进行预约
                                        if(validatePreTime && DateUtils.getNowDate().before(DateUtils.parseDate(compileTime))){
                                            int count = iWebServerOrderService.count(new QueryWrapper<WebServerOrder>()
                                                    .eq("server_user_id", serverUserId)
                                                    .eq("dept_id", deptId)
                                                    .eq("pre_day", preDay)
                                                    .ne("status",3)
                                                    .eq("pre_time",d_));
                                            if(count > 0){
                                                throw new BusinessException("抱歉，当前时间段不可预约"+recycleType.getName());
                                            }
                                        }


                                        while (it.hasNext()) {
                                            String ordre = it.next();
                                            if (ordre.equals(d_)) {
                                                it.remove();
                                            }
                                        }

                                    }
                                }
                        }
                    }
                    it = timeList.iterator();
                    while (it.hasNext()) {
                        String ordre = it.next();
                        if (ordre.equals(order.getPreTime())) {
                            it.remove();
                        }
                    }
                }


                timeList2 = timeList;
            }
        }
        return timeList2;
    }

    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ISysDeptService iSysDeptService;
    @Autowired
    private IWebRecycleTypeService webRecycleTypeService;
    @Autowired
    private IWebServerOrderService iWebServerOrderService;
    @Autowired
    private IWebServerUserService iWebServerUserService;
}
